package org.goldfish.cookied_chatroom02.utils;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.goldfish.cookied_chatroom02.model.LoginParams;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Utils {
    @NotNull
    public static Map<String, String> getCookiesMap(
            @NotNull HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        if (request.getCookies() == null) return map;
        for (Cookie cookie : request.getCookies()) {
            map.put(cookie.getName(), cookie.getValue());
        }
        return map;
    }

    public static Map<String, String> parseFormPostInputStream(
            InputStream stream)
            throws IOException {
        StringBuffer buffer = new StringBuffer();
        int c;
        while ((c = stream.read()) != -1) {
            buffer.append((char) c);
        }
        Map<String, String> formMap = new HashMap<>();
        for (String line : buffer.toString()
                .split("&")) {
            String[] pair = line.split("=");
            if (pair.length != 2) continue;
            formMap.put(pair[0], pair[1]);
        }
        return formMap;
    }

    public static void warn(String message, HttpServletRequest request) {
        String message_existing = (String) request.getAttribute(LoginParams.ERROR_MSG);
        request.setAttribute(LoginParams.ERROR_MSG, message + "\t\n" + (message_existing == null ? "" : message_existing));
    }


    public static void initLoginSessionRecorder(@NotNull ServletContext context) {
        if (getLoggedInSessions(context) != null) return;
        HashMap<String, String> map = new HashMap<>();
        context.setAttribute(LoginParams.LOGGED_IN_SESSIONS, map);
    }

    @Nullable
    public static HashMap<String, String> getLoggedInSessions(@NotNull ServletContext context) {
        try {
            return (HashMap<String, String>) context.getAttribute(LoginParams.LOGGED_IN_SESSIONS);
        } catch (ClassCastException e) {
            return null;
        }
    }
}
